/* Copyright (c) 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.inject.Inject;
import com.google.orkut.client.api.samples.greetings.shared.AuthorizationException;
import com.google.orkut.client.api.samples.greetings.shared.CommonConstants;

/**
 * A callback wrapper that executes common checks and catches known exceptions.
 * At present, it only catches {@link AuthorizationException} and shows a popup
 * and redirects to login page.
 *
 * @author Shishir Birmiwal
 */
public class GreetingsCallbackWrapper {
  private final GreetingsMessages msgs;

  @Inject
  public GreetingsCallbackWrapper(GreetingsMessages msgs) {
    this.msgs = msgs;
  }

  public <T> AsyncCallback<T> wrap(final AsyncCallback<T> cb) {
    return new AsyncCallback<T>() {
      private DialogBox box;

      @Override
      public void onFailure(Throwable arg0) {
        if (arg0 instanceof AuthorizationException) {
          String redirectUrl = Window.Location.getProtocol() + "//" + Window.Location.getHost() + CommonConstants.LOGIN_PATH;
          box = getRedirectDialogBox(redirectUrl);
          box.show();
          return;
        }
        cb.onFailure(arg0);
      }

      @Override
      public void onSuccess(T arg0) {
        cb.onSuccess(arg0);
      }
    };
  }

  DialogBox getRedirectDialogBox(final String redirectUrl) {
    DialogBox box = new DialogBox();
    box.setText(msgs.loginRequired());
    VerticalPanel panel = new VerticalPanel();
    box.setWidget(panel);
    panel.add(new HTML(msgs.loginMessage()));
    Button b = new Button(msgs.loginButton());
    panel.add(b);
    b.addClickHandler(new ClickHandler() {
      @Override
      public void onClick(ClickEvent arg0) {
        Cookies.removeCookie(CommonConstants.COOKIE);
        Window.Location.replace(redirectUrl);
      }
    });
    box.center();
    box.setAnimationEnabled(true);
    box.setGlassEnabled(true);
    return box;
  }
}
